package com.we.flink.userlabelplatform.table;

import org.apache.flink.api.common.functions.FilterFunction;
import org.apache.flink.api.common.functions.RichFlatMapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.util.Collector;

import com.alibaba.fastjson.JSONObject;

import java.sql.Timestamp;

public class TableUserEntrepreneurRecord {
    public static final String KFKTABLE = "fdm.hhl01_user_entrepreneur_record";
    public static final String QUERYSQL =
            "select uid, "
                    + "is_entrepreneur, create_time"
                    + " from "
                    + KFKTABLE
                    + " where uid is not null "
                    + "and is_entrepreneur is not null "
                    + "and create_time is not null";

    public long uid;
    public int is_entrepreneur;
    public Timestamp create_time;

    public TableUserEntrepreneurRecord() {}

    public TableUserEntrepreneurRecord(long uid, int is_entrepreneur, Timestamp create_time) {
        this.uid = uid;
        this.is_entrepreneur = is_entrepreneur;
        this.create_time = create_time;
    }

    public static TableUserEntrepreneurRecord init(Long uid) {
        return new TableUserEntrepreneurRecord(
                uid, -1, Timestamp.valueOf("1970-01-01 08:00:00.000000"));
    }

    public static SingleOutputStreamOperator<String> getFlatMapStream(
            StreamTableEnvironment tableEnv, StreamExecutionEnvironment env) {
        Table tableRes = tableEnv.sqlQuery(TableUserEntrepreneurRecord.QUERYSQL);
        DataStream<Tuple2<Boolean, TableUserEntrepreneurRecord>> inputStream =
                tableEnv.toRetractStream(tableRes, TableUserEntrepreneurRecord.class);

        SingleOutputStreamOperator<String> out =
                inputStream
                        .filter(
                                new FilterFunction<Tuple2<Boolean, TableUserEntrepreneurRecord>>() {
                                    @Override
                                    public boolean filter(
                                            Tuple2<Boolean, TableUserEntrepreneurRecord> value)
                                            throws Exception {
                                        return value.f0;
                                    }
                                })
                        .uid("TagUserEntrepreneurRecord-filter")
                        .keyBy(
                                new KeySelector<
                                        Tuple2<Boolean, TableUserEntrepreneurRecord>, Long>() {
                                    @Override
                                    public Long getKey(
                                            Tuple2<Boolean, TableUserEntrepreneurRecord> value)
                                            throws Exception {
                                        return value.f1.getUid();
                                    }
                                })
                        .flatMap(
                                new RichFlatMapFunction<
                                        Tuple2<Boolean, TableUserEntrepreneurRecord>, String>() {
                                    ValueState<TableUserEntrepreneurRecord>
                                            userEntrepreneurRecordVState;

                                    @Override
                                    public void open(Configuration parameters) throws Exception {
                                        userEntrepreneurRecordVState =
                                                getRuntimeContext()
                                                        .getState(
                                                                new ValueStateDescriptor<
                                                                        TableUserEntrepreneurRecord>(
                                                                        "UserEntrepreneurRecordVState",
                                                                        TableUserEntrepreneurRecord
                                                                                .class));
                                    }

                                    @Override
                                    public void flatMap(
                                            Tuple2<Boolean, TableUserEntrepreneurRecord> value,
                                            Collector<String> out)
                                            throws Exception {
                                        long uid = value.f1.getUid();
                                        int is_entrepreneur = value.f1.getIs_entrepreneur();
                                        Timestamp create_time = value.f1.getCreate_time();

                                        TableUserEntrepreneurRecord tmpState =
                                                userEntrepreneurRecordVState.value();
                                        TableUserEntrepreneurRecord curState =
                                                tmpState == null
                                                        ? TableUserEntrepreneurRecord.init(uid)
                                                        : tmpState;

                                        if (curState.getCreate_time().getTime()
                                                        < create_time.getTime()
                                                && curState.getIs_entrepreneur()
                                                        != is_entrepreneur) {
                                            JSONObject jsonObject = new JSONObject();
                                            jsonObject.put("uid", uid);
                                            jsonObject.put("is_entrepreneur", is_entrepreneur);
                                            out.collect(jsonObject.toString());

                                            curState.create_time = create_time;
                                            curState.is_entrepreneur = is_entrepreneur;
                                            userEntrepreneurRecordVState.update(curState);
                                        }
                                    }
                                });

        return out;
    }

    public long getUid() {
        return uid;
    }

    public Timestamp getCreate_time() {
        return create_time;
    }

    public int getIs_entrepreneur() {
        return is_entrepreneur;
    }
}
